package com.demo.interceptor;

import com.demo.common.Constants;
import com.demo.exception.ServiceException;
import com.demo.util.CurrentUtil;
import com.demo.util.JwtUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求的接口方法是否带有 @AuthAccess 注解。如果带有该注解，则直接放行
        if(handler instanceof HandlerMethod) {
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (annotation != null) {
                return true;
            }
        }

        // 获取请求头中的token
        String token = request.getHeader("token");

        // 判断请求头中是否有token，如果没有，则直接拒绝访问
        if (StrUtil.isEmpty(token)){
            throw new ServiceException(Constants.AJAX_UNAUTHORIZED, "请先登录再操作！");
        }

        // 如果有token，则判断是否有效
        if (!JwtUtil.valid(token)){
            throw new ServiceException(Constants.AJAX_UNAUTHORIZED, "token无效，请重新登录！");
        }

        // 获取用户id，并保存到ThreadLocal中
        CurrentUtil.setUserId(JwtUtil.decodeInteger(token, "id"));

        return true;
    }
}
